package com.neusoft.dibuy.tyut.net.util;

import com.neusoft.dibuy.tyut.net.cfg.NetConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

@Data
@AllArgsConstructor
@NoArgsConstructor
/**
 * TODO :  实现将磁盘文件写入网线
 */
public class File2NetTool {
    private String fileName;
    private String ip;
    private int port;

    public File2NetTool(String fileName, String ip, int port) {
        this.fileName = fileName;
        this.ip = ip;
        this.port = port;
    }


    public long sendFile()   {
        File  file =new File(fileName);
        if (!file.exists()){
            return -1;
        }
        try {
            Socket socket =new Socket(ip,port);
            return   sendFile(socket,file);

        } catch (IOException e) {
            return   -1;
        }
    }

    private long sendFile(Socket socket, File file) {
        long l =-1;
        FileInputStream fis = null;
        OutputStream os =null;

        try {
              fis =new FileInputStream(file);
              os = socket.getOutputStream();

            byte[] bs =new byte[NetConfig.MSG_LENGTH];
            while (true){
                int len = fis.read(bs);
                if (len==-1){
                    break;
                }
                os.write(bs,0,len);
//                强制输出
                os.flush();
//                累计字节数
                l+=len;
                System.out.println( "已经传输 ： " + l + "byte"  );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (fis!=null)
                    fis.close();
                if (os!=null)
                    os.close();
                socket.close();
            }catch (IOException e){

            }
        }
        return  l;
    }
}